package dbs

import (
	"DCOS-API/utils"
	"fmt"
	"github.com/jinzhu/gorm"
	"time"
	"DCOS-API/config"
)

var (
	db *gorm.DB
)

func Mysql() *gorm.DB {
	if db == nil {
		var (
			err  error
			conf = config.GetConfig()
			mysqlConf = conf.Mysql

		)
		mysqlConf.Pass, err = utils.AesDe(mysqlConf.Pass, conf.BaseConfig.SignKey)
		if err != nil {
			panic(fmt.Errorf("解密mysql密码(%v)错误！", mysqlConf.Pass))
		}
		url  := fmt.Sprintf(mysqlConf.Addr, mysqlConf.User, mysqlConf.Pass, mysqlConf.DB)
		db, err = gorm.Open("mysql", url)
		db.LogMode(true)
		db.DB().SetMaxIdleConns(mysqlConf.Idle)
		db.DB().SetMaxOpenConns(mysqlConf.Active)
		db.DB().SetConnMaxLifetime(time.Second * 300)
		//这里的表基本是复数形式
		db.SingularTable(true)
		if err != nil {
			panic(err)
		}
	}
	return db
}
